"""
SQL编译器主类
整合词法分析器、语法分析器和语义分析器
"""

from .lexer import SQLLexer
from .parser import SQLParser
from .semantic import SemanticAnalyzer

class SQLCompiler:
    """SQL编译器"""
    
    def __init__(self):
        """初始化编译器"""
        self.lexer = SQLLexer()
        self.parser = SQLParser()
        self.semantic_analyzer = SemanticAnalyzer()
    
    def compile(self, sql_text):
        """编译SQL语句"""
        try:
            # 词法分析
            tokens = self.lexer.tokenize(sql_text)
            if not tokens:
                raise Exception("词法分析失败: 没有找到有效的token")
            
            # 语法分析
            ast = self.parser.parse(sql_text)
            if not ast:
                raise Exception("语法分析失败: 无法构建AST")
            
            # 语义分析
            result = self.semantic_analyzer.analyze(ast)
            if self.semantic_analyzer.has_errors():
                errors = self.semantic_analyzer.get_errors()
                raise Exception(f"语义分析失败: {'; '.join(errors)}")
            
            return result
            
        except Exception as e:
            raise Exception(f"编译失败: {str(e)}")
    
    def get_schema(self):
        """获取数据库模式"""
        return self.semantic_analyzer.get_schema()
    
    def print_schema(self):
        """打印数据库模式"""
        self.semantic_analyzer.print_schema()
    
    def test_compilation(self, sql_text):
        """测试编译过程"""
        print(f"SQL: {sql_text}")
        print("-" * 50)
        
        try:
            # 词法分析
            print("1. 词法分析:")
            tokens = self.lexer.tokenize(sql_text)
            for token in tokens:
                print(f"   {token.type}: {token.value}")
            
            # 语法分析
            print("\n2. 语法分析:")
            ast = self.parser.parse(sql_text)
            if ast:
                print("   AST构建成功")
                self.parser.print_ast(ast, 1)
            else:
                print("   AST构建失败")
                return None
            
            # 语义分析
            print("\n3. 语义分析:")
            result = self.semantic_analyzer.analyze(ast)
            if self.semantic_analyzer.has_errors():
                print("   语义错误:")
                for error in self.semantic_analyzer.get_errors():
                    print(f"     - {error}")
                return None
            else:
                print("   语义分析成功")
                return result
                
        except Exception as e:
            print(f"编译错误: {str(e)}")
            return None

# 测试函数
if __name__ == "__main__":
    compiler = SQLCompiler()
    
    # 测试用例
    test_cases = [
        "CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(50), age INT)",
        "INSERT INTO users VALUES (1, 'Alice', 25)",
        "SELECT * FROM users WHERE age > 20",
        "UPDATE users SET age = 26 WHERE id = 1",
        "DELETE FROM users WHERE age < 18",
        "DROP TABLE users"
    ]
    
    for test_case in test_cases:
        print("\n" + "="*60)
        result = compiler.test_compilation(test_case)
        if result:
            print(f"\n编译结果: {result['type']}")
    
    print("\n" + "="*60)
    print("最终数据库模式:")
    compiler.print_schema()
